#include "iringbuf.h"

#define IRINGBUF_ITEMS 12
#define IRINGBUF_WIDTH 128
static char iringbuf[IRINGBUF_ITEMS][IRINGBUF_WIDTH];
static int front = 0, rear = 0;
static inline bool iringbuf_full() {
    if ((rear+1) % IRINGBUF_ITEMS == front) {
        return true;
    }
    return false;
}

void iringbuf_wirte(char* logstr) {
    // 覆盖一项旧数据
    if (iringbuf_full()) {
        front = (front + 1) % IRINGBUF_ITEMS;
    }
    // wirte
    strncpy(iringbuf[rear], logstr, IRINGBUF_WIDTH);
    rear = (rear + 1) % IRINGBUF_ITEMS;
}

void iringbuf_print() {
    printf(ANSI_FMT("=============== <Latest %d instructions> ===============\n", ANSI_FG_RED), IRINGBUF_ITEMS);
    int i = front;
    while (i != rear) {
        printf("%s", iringbuf[i]);
        i = (i + 1) % IRINGBUF_ITEMS;
        if (i == rear) {
            printf("\t <----");
        }
        printf("\n");
    }
    printf(ANSI_FMT("=============== <Latest %d instructions> ===============\n\n", ANSI_FG_RED), IRINGBUF_ITEMS);
    // clear iringbuf
    front = 0, rear = 0;
}
